// pages/party/party.js
const util = require('../../utils/util.js');
const qiniu = require("../../utils/qiniu.min.js");
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    concern: false,
    text: '关注"一起来往"公众号，及时享受活动提醒服务。',
    userInfo: '',
    act: {
      id: '',
      actType: 0, //自定义活动
      topic: '',
      actPoster: '',
      actAddress: '',
      longitude: '',
      latitude: '',
      provinceId: '',
      cityId: '',
      districtId: '',
      chooseConsume: 1,
      perCapita: '',
      payer: '',
      actStartTime: '',
      actEndTime: '',
      seat: '',
      isName: 1,
      isTelphone: 1,
      isSex: 0,
      isWechatNum: 0,
      isIdcard: 0,
      isCusromize: '',
      regimentSize: 0,
      perUpperLimit: 0,
      applyEndTime: '',
      isCheck: 0,
      transportation: '',
      signInWay: '',
      activityProcess: '',
      remark: '',
      invitationPeriod: 0
    },
    showStart: false,
    currentStartDate: new Date().getTime(),
    showEnd: false,
    currentEndDate: new Date().getTime(),
    addType: '姓名、手机号',
    remarkStr: '请设置',
    actStartTimeLong: 0,
    actStartTimeStr: '必填',
    actEndTimeLong: 0,
    actEndTimeStr: '必填',
    imgUrls: [
      '/img/temp.png'
    ],
    current: 0,
    btnText: '制作邀请函',
    dateFlag: false,
    peoplePanelFlag: false,
    peopelFlag: false,
    tranFlag: false,
    signFlag: false,
    activityFlag: false,
    applyEndTimeStr: '选填',
    currentApplyEndDate: new Date().getTime(),
    activityProcessStr: '',
    activityProcess: '',
    tranList: [],
    signInList: [],
    columns: [{
        values: [],
        className: 'column1'
      },
      {
        values: ['不限'].concat(Array.from({
          length: 100
        }, (v, k) => k + 1)),
        className: 'column2'
      },
      {
        values: ['至'],
        className: 'column3'
      },
      {
        values: ['不限'].concat(Array.from({
          length: 100
        }, (v, k) => k + 1)),
        className: 'column4'
      }, {
        values: [],
        className: 'column5'
      }
    ]
  },
  deleteArea() {
    this.toggle('act.actAddress', '');
    this.toggle('act.longitude', '');
    this.toggle('act.latitude', '');
  },
  getTranList(options) {
    var that = this;
    app.req({
      url: 'wechat/dictionary/listBydictType',
      data: {
        dictType: 'ACT_TRANSPORT'
      },
      method: 'POST',
      success: function(res) {
        if (res.code == 200) {
          that.setData({
            tranList: res.data
          })
          if (options.transportation && options.transportation != '') {
            let transportation = ',' + options.transportation + ',',
              tranList = res.data;
            for (let item of tranList) {
              item.isChoose = transportation.indexOf(',' + item.dictValue + ',') >= 0;
            }
            that.setData({
              tranList: tranList,
              tranFlag: true
            })
            that.toggle('act.transportation', options.transportation);
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  getSignInList(options) {
    var that = this;
    app.req({
      url: 'wechat/dictionary/listBydictType',
      data: {
        dictType: 'PUNCH_IN'
      },
      method: 'POST',
      success: function(res) {
        if (res.code == 200) {
          that.setData({
            signInList: res.data
          })
          if (options.signInWay && options.signInWay != '') {
            let signIn = ',' + options.signInWay + ',',
              signInList = res.data;
            for (let item of signInList) {
              item.isChoose = signIn.indexOf(',' + item.dictValue + ',') >= 0;
            }
            that.setData({
              signInList: signInList,
              signFlag: true
            })
            that.toggle('act.signInWay', options.signInWay);
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  tapPeople(e) {
    this.setData({
      peoplePanelFlag: !this.data.peopelFlag,
      peopelFlag: !this.data.peopelFlag,
    })
    this.toggle('act.regimentSize', !this.data.peopelFlag ? 0 : this.data.act.regimentSize);
    this.toggle('act.perUpperLimit', !this.data.peopelFlag ? 0 : this.data.act.perUpperLimit);
  },
  tapPeopleText(e) {
    this.setData({
      peoplePanelFlag: true
    })
  },
  peopleConfirm(e) {
    let regimentSize = e.detail.value[1] == '不限' ? -1 : e.detail.value[1],
      perUpperLimit = e.detail.value[3] == '不限' ? -1 : e.detail.value[3],
      min = regimentSize,
      max = (perUpperLimit == -1 ? 999 : perUpperLimit);
    if (min > max) {
      wx.showToast({
        title: '人员上限应大于人员下限',
        icon: 'none',
        duration: 2000
      })
    } else {
      this.toggle('act.regimentSize', regimentSize);
      this.toggle('act.perUpperLimit', perUpperLimit);
      this.peopleCancel();
    }
  },
  peopleCancel(e) {
    this.setData({
      peoplePanelFlag: false
    })
  },
  tapCheck() {
    this.toggle('act.isCheck', this.data.act.isCheck == 0 ? 1 : 0);
  },
  swiperChange(e) {
    this.setData({
      current: e.detail.current
    })
    this.toggle('act.actPoster', this.data.imgUrls[e.detail.current])
  },
  changeBg() {
    var that = this;
    app.getQiNiuToken(function(res) {
      var qiniuconfig = res;
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album'],
        success: function(res) {
          const filepath = res.tempFilePaths[0]
          qiniu.upload(filepath, res => {
            var imgList = that.data.imgUrls;
            imgList.push(res.imageURL);
            that.setData({
              current: imgList.length - 1,
              imgUrls: imgList
            });
          }, (error) => {
            console.log('error' + error)
          }, {
            uploadURL: 'https://upload.qiniup.com',
            region: 'ECN',
            domain: qiniuconfig.qiniuDomain,
            uptoken: qiniuconfig.upToken,
          })
        }
      })
    });
  },
  //设置主题
  setTitle() {
    wx.navigateTo({
      url: '/pages/partyTitle/partyTitle?topic=' + this.data.act.topic
    });
  },
  //开始时间事件
  openStartDate() {
    this.setData({
      showStart: true
    })
  },
  onStartConfirm(event) {
    this.toggle('act.actStartTime', util.formatTime3(event.detail))
    this.toggle('actStartTimeLong', event.detail)
    this.toggle('actStartTimeStr', util.formatTime4(event.detail))
    this.closeStartDate();
  },
  closeStartDate() {
    this.setData({
      showStart: false
    })
  },
  //结束时间事件
  openEndDate() {
    this.setData({
      showEnd: true
    })
  },
  onEndConfirm(event) {
    this.toggle('act.actEndTime', util.formatTime3(event.detail))
    this.toggle('actEndTimeLong', event.detail)
    this.toggle('actEndTimeStr', util.formatTime4(event.detail))
    this.closeEndDate();
  },
  closeEndDate() {
    this.setData({
      showEnd: false
    })
  },
  //聚会地点
  openGPS() {
    var that = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success: function() {
              that.realOpenGPS();
            },
            fail: function(d) {
              wx.showModal({
                title: '获取授权失败',
                content: '是否前往设置允许小程序使用位置信息',
                success(res) {
                  if (res.confirm) {
                    wx.openSetting({
                      complete: function(r) {
                        if (r.authSetting['scope.userLocation']) {
                          that.realOpenGPS();
                        }
                      }
                    });
                  }
                }
              })
            }
          })
        } else {
          that.realOpenGPS();
        }
      }
    });
  },
  realOpenGPS() {
    var that = this;
    wx.chooseLocation({
      success: function(res) {
        that.toggle('act.actAddress', res.name);
        that.toggle('act.longitude', res.longitude);
        that.toggle('act.latitude', res.latitude);
        that.toggle('act.actAddress2', res.address);
      },
      fail(res) {
        console.log(res)
      }
    });
  },
  //设置席位
  setSeat() {
    wx.navigateTo({
      url: '/pages/partySeat/partySeat?seat=' + this.data.act.seat
    });
  },
  //人均费用
  setFee() {
    var userId = this.data.userInfo.id;
    var act = this.data.act;
    if (act.id && act.list && 1 == act.chooseConsume) {
      for (let item of act.list) {
        if (item.participantId != userId) {
          return;
        }
      }
    }
    wx.navigateTo({
      url: '/pages/partyFee/partyFee?perCapita=' + this.data.act.perCapita +
        '&payer=' + this.data.act.payer +
        '&chooseConsume=' + this.data.act.chooseConsume
    })
  },
  //报名方式
  setAddType() {
    wx.navigateTo({
      url: '/pages/partyAddType/partyAddType?isName=' + this.data.act.isName +
        '&isTelphone=' + this.data.act.isTelphone +
        '&isSex=' + this.data.act.isSex +
        '&isWechatNum=' + this.data.act.isWechatNum +
        '&isIdcard=' + this.data.act.isIdcard +
        '&isCusromize=' + this.data.act.isCusromize
    })
  },
  tapApplyEndTime() {
    this.setData({
      dateFlag: true
    })
  },
  onApplyEndTimeConfirm(event) {
    this.toggle('act.applyEndTime', event.detail);
    this.toggle('act.applyEndTimeStr', util.formatTime4(event.detail));
    this.closeEndTime();
  },
  closeApplyEndTime() {
    this.setData({
      dateFlag: false
    })
  },
  tapTran() {
    this.setData({
      tranFlag: !this.data.tranFlag
    })
  },
  tapSign() {
    this.setData({
      signFlag: !this.data.signFlag
    })
  },
  tapActivityProcess() {
    if (!this.data.activityFlag) {
      wx.navigateTo({
        url: '/pages/partySettingMemo/partySettingMemo?activityProcess=' + this.data.activityProcess
      })
    } else {
      this.setData({
        activityFlag: !this.data.activityFlag
      })
    }
  },
  tapActivityProcessText() {
    wx.navigateTo({
      url: '/pages/partySettingMemo/partySettingMemo?activityProcess=' + this.data.activityProcess
    })
  },
  tapRadio(e) {
    let name = e.currentTarget.dataset.name,
      ischoose = e.currentTarget.dataset.ischoose,
      value = e.currentTarget.dataset.value;
    this.toggle([name], !ischoose);
  },
  //设置备注
  setRemark() {
    wx.navigateTo({
      url: '/pages/partyMemo/partyMemo?remark=' + this.data.act.remark
    })
  },
  invitation() {
    var that = this;
    var data = this.data.act;
    //校验地址、主题、开始结束时间必填
    // if (data.topic == '') {
    //   wx.showToast({
    //     title: '请输入活动主题',
    //     icon: 'none',
    //     duration: 2000
    //   })
    //   return;
    // }
    if (data.actStartTime == '') {
      wx.showToast({
        title: '请选择开始时间',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (data.actEndTime == '') {
      wx.showToast({
        title: '请选择结束时间',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    // if (data.latitude == '' || data.longitude == '' || data.actAddress == '') {
    //   wx.showToast({
    //     title: '请选择地点',
    //     icon: 'none',
    //     duration: 2000
    //   })
    //   return;
    // }
    //校验人均费用必选一个
    if (data.perCapita == '' && data.payer == '') {
      wx.showToast({
        title: '请填写' + (data.chooseConsume == 1 ? '人均费用' : '请客人'),
        icon: 'none',
        duration: 2000
      })
      return;
    }
    //打开人员限制则必填
    if (this.data.peopelFlag && (data.regimentSize == 0 || data.perUpperLimit == 0)) {
      wx.showToast({
        title: '请选择人员限制',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    //校验开始时间大于当前时间
    if (1 != this.data.act.status && this.data.actStartTimeLong < new Date().getTime()) {
      wx.showToast({
        title: '活动开始时间必须大于当前时间',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    //校验开始时间小于结束时间
    if (this.data.actStartTimeLong >= this.data.actEndTimeLong) {
      wx.showToast({
        title: '活动结束时间必须大于活动开始时间',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    //校验结束时间大于当前时间
    if (this.data.actEndTimeLong < new Date().getTime()) {
      wx.showToast({
        title: '活动结束时间必须大于当前时间',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    //活动报名截止日期为空则默认为活动结束时间
    if (data.applyEndTime == '') {
      data.applyEndTime = this.data.actEndTimeLong;
    }

    //报名截止时间小于等于活动结束时间
    if (1 != this.data.act.status && data.applyEndTime * 1 > this.data.actEndTimeLong) {
      wx.showToast({
        title: '报名截止时间必须小于活动结束时间',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    //将时间戳改为系统时间
    data.applyEndTime = util.formatTime3(data.applyEndTime);
    //获得选中的背景图
    data.actPoster = this.data.imgUrls[this.data.current];
    //交通方式
    if (this.data.tranFlag) {
      let transportation = [];
      for (let item of this.data.tranList) {
        if (item.isChoose) {
          transportation.push(item.dictValue);
        }
      }
      if (transportation.length == 0) {
        wx.showToast({
          title: '请选择交通工具',
          icon: 'none',
          duration: 2000
        })
        return;
      } else {
        data.transportation = transportation.join(',');
      }
    }
    //签到方式
    if (this.data.signFlag) {
      let signIn = [];
      for (let item of this.data.signInList) {
        if (item.isChoose) {
          signIn.push(item.dictValue);
        }
      }
      if (signIn.length == 0) {
        wx.showToast({
          title: '请选择打卡签到方式',
          icon: 'none',
          duration: 2000
        })
        return;
      } else {
        data.signInWay = signIn.join(',');
      }
    }
    //活动流程
    if (this.data.activityFlag && this.data.activityProcess == '') {
      wx.showToast({
        title: '请输入活动流程',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    //将外层的活动详情赋值给数据接口
    data.activityProcess = this.data.activityProcess;
    if (data.topic == '') {
      data.topic = '好久不见,一起吃个饭吧!';
    }
    if (data.id == '') {
      this.addAct(data);
    } else {
      this.uptAct(data);
    }
  },
  onClose: function() {
    this.setData({
      showPay: false,
    });
  },
  addAct(actData) {
    if (this.data.id && this.data.act.chooseConsume == 1) {
      this.setData({
        showPay: true
      });
      return;
    }
    var that = this;
    app.req({
      url: 'wechat/activity/addActivity',
      data: actData,
      method: 'POST',
      success: function(res) {
        if (res.code == 200) {
          if (that.data.act.chooseConsume == 1) {
            that.setData({
              id: res.data.id,
              showPay: true
            });
          } else {
            wx.navigateTo({
              url: '/pages/partyInvitation/partyInvitation?isBack=1&id=' + res.data.id
            });
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  pay() {
    if (this.data.act.chooseConsume == 1) {
      var that = this;
      app.req({
        url: "wechat/wxpay/pay",
        method: "post",
        data: {
          activityId: that.data.id
        },
        success: function(res) {
          if (res.code == 200) {
            var paydata = res.data;
            wx.requestPayment({
              timeStamp: paydata.prepayDate.timeStamp,
              nonceStr: paydata.prepayDate.nonceStr,
              package: 'prepay_id=' + paydata.prepayDate.prepay_id,
              signType: 'MD5',
              paySign: paydata.prepayDate.paySign,
              success(res) {
                app.req({
                  url: "wechat/activity/addAccount",
                  method: "post",
                  data: {
                    id: that.data.id,
                    outTradeNo: paydata.outTradeNo
                  },
                  success: function(res) {
                    if (res.code == 200) {
                      wx.navigateTo({
                        url: '/pages/partyInvitation/partyInvitation?isBack=1&id=' + that.data.id
                      });
                    } else {
                      wx.showToast({
                        title: res.msg,
                        icon: 'none',
                        duration: 2000
                      })
                    }
                  }
                })

              },
              fail(res) {
                console.log(res.errMsg)
              }
            })
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      });
    }
  },
  uptAct(actData) {
    app.req({
      url: 'wechat/activity/updateActivity',
      data: actData,
      method: 'POST',
      success: function(res) {
        if (res.code == 200) {
          wx.navigateBack({
            delta: 1
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  toggle(type, val) {
    this.setData({
      [type]: val
    });
  },

  //获得默认背景图
  getBgImgList(img) {
    var that = this;
    app.req({
      url: 'wechat/image/list',
      data: {
        "type": 0
      },
      method: 'POST',
      success: function(res) {
        if (res.code == 200) {
          var imgList = [],
            current = 0,
            exists = false;
          for (let i in res.data) {
            let item = res.data[i];
            imgList.push(item.url);
            if (item.url == img) {
              current = i;
              exists = true;
            }
          }
          if (img && img != '' && !exists) {
            imgList.push(img);
            current = imgList.length - 1;
          }
          that.setData({
            imgUrls: imgList,
            current: current,
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  //获得活动详情
  getActInfo(id, isCopy) {
    var that = this;
    app.req({
      url: 'wechat/activity/activityDetail',
      data: {
        "id": id
      },
      method: 'POST',
      success: function(res) {
        if (res.code == 200) {
          var data = res.data,
            startDate = util.formatDate(data.actStartTime),
            endDate = util.formatDate(data.actEndTime),
            applyEndDate = util.formatDate(data.applyEndTime),
            count = data.isSex + data.isWechatNum + data.isIdcard + (data.isCusromize == '' ? 0 : 1),
            peopelFlag = data.regimentSize != 0 && data.perUpperLimit != 0;
          data.applyEndTime = applyEndDate;
          if (isCopy == 1) {
            data.id = '';
          }
          that.setData({
            act: data,
            currentStartDate: startDate,
            currentEndDate: endDate,
            addType: '姓名、手机号' + (count > 0 ? '等' : ''),
            remarkStr: data.remark == '' ? '请设置' : util.subRemark(data.remark),
            actStartTimeLong: startDate,
            actStartTimeStr: util.formatTime4(startDate),
            actEndTimeLong: endDate,
            actEndTimeStr: util.formatTime4(endDate),
            currentEndDate: endDate,
            actEndTimeLong: endDate,
            actEndTimeStr: util.formatTime4(endDate),
            applyEndTimeStr: util.formatTime4(applyEndDate),
            currentApplyEndDate: applyEndDate,
            activityFlag: data.activityProcess != '',
            activityProcessStr: util.subRemark(data.activityProcess),
            activityProcess: data.activityProcess,
            btnText: '完成',
            peopelFlag: peopelFlag
          });
          that.getTranList({
            transportation: data.transportation
          });
          that.getSignInList({
            signInWay: data.signInWay
          });
          that.getBgImgList(data.actPoster);
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  //是否关注公众号
  concernWechat: function() {
    var that = this;
    app.req({
      url: "wechat/sys/register",
      method: "post",
      success: function(res) {
        // that.toggle("concern", !!res);
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    app.getUserInfo(function(userInfo) {
      that.setData({
        userInfo: userInfo
      })
      that.concernWechat();
    })
    if (options.id && options.id != '') {
      this.getActInfo(options.id, options.isCopy);
    } else {
      this.getTranList(options);
      this.getSignInList(options);
      this.getBgImgList();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  }
})